package com.smscenter.server.core.welink;


import com.smscenter.server.core.IQuery;
import com.zeus.base.smscenter.common.constant.SmsConstants;
import com.zeus.base.smscenter.common.constant.WelinkConstants;
import com.zeus.base.smscenter.common.util.DateTimeUtils;
import com.zeus.base.smscenter.common.util.WebUtils;
import com.zeus.base.smscenter.common.util.StringUtils;
import com.zeus.base.smscenter.common.util.XMLParser;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微网通联查询实现类
 * @author: hailong
 * @date： 2016年10月19日
 *
 */
public class WelinkQuery implements IQuery {
	
	public static void main(String[] args) throws Exception {
		WelinkQuery w = new WelinkQuery();
		Map map = new HashMap();
		map.put("loginName", "dlherbfy");
		map.put("loginPassword", "Z0nbGe9y");
		map.put("startTime", "20161020000000");
		System.out.println(w.queryBalance(map));;
//		Map m = JSON.parseObject("{\"accountName\":\"dlherbfy\",\"balance\":\"999981\"}");
//		System.out.println(m.get("accountName"));
	}
	
    @Override
    public String queryBalance(Map<String, Object> params) throws Exception {
        String sname = params.get("loginName")==null ? "":params.get("loginName").toString();
        String spwd = params.get("loginPassword")==null ? "":params.get("loginPassword").toString();
        if (StringUtils.isEmpty(sname)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(spwd)){
            throw  new Exception("参数:租户密码系统错误:error:租户密码不能为空");
        }
        
        Map<String,String> requestMap=new HashMap<String, String>();
        requestMap.put("sname",sname);
        requestMap.put("spwd",spwd);
        requestMap.put("scorpid","");
        requestMap.put("sprdid", WelinkConstants.SPRDID);
        
        String returnMsg = "";
        try {
        	returnMsg = WebUtils.doPost(WelinkConstants.SEARCH_BALANCE_URL,WebUtils.buildAllQuery(requestMap, SmsConstants.CHARSET_UTF8), SmsConstants.CHARSET_UTF8, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }

        StringBuffer returnJson = new StringBuffer().append("{");
        String state = null;
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "CRemain");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
                state = parser.getString(root,"State");
                String balance = parser.getString(root,"Remain");
                if(!StringUtils.isEmpty(balance) && params.get("unitPrice") != null){
                    balance = Double.toString(Double.parseDouble((String) params.get("unitPrice")) * Double.parseDouble(balance));
                }
                if (i==0){
                    returnJson.append("\"accountName\"").append(":\"").append(sname).append("\",");
                    returnJson.append("\"balance\"").append(":\"").append(balance).append("\"");
                }
            }
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        if("-99".equals(state)){
        	throw  new Exception("短信平台异常");
        }
        if("-3".equals(state)){
        	throw  new Exception("用户名或者密码不正确");
        }
        if("-4".equals(state)){
        	throw  new Exception("产品编号不正确");
        }
        returnJson.append("}");
        return returnJson.toString();
    }
    
    @Override
    public String queryBalanceV2(Map<String, Object> params) throws Exception {
        String sname = params.get("loginName")==null ? "":params.get("loginName").toString();
        String spwd = params.get("loginPassword")==null ? "":params.get("loginPassword").toString();
        if (StringUtils.isEmpty(sname)){
            throw  new Exception("参数:租户名系统错误:error:租户名不能为空");
        }
        if (StringUtils.isEmpty(spwd)){
            throw  new Exception("参数:租户密码系统错误:error:租户密码不能为空");
        }
        
        Map<String,String> requestMap=new HashMap<String, String>();
        requestMap.put("sname",sname);
        requestMap.put("spwd",spwd);
        requestMap.put("scorpid","");
        requestMap.put("sprdid",WelinkConstants.SPRDID);
        
        String returnMsg = "";
        try {
        	returnMsg = WebUtils.doPost(WelinkConstants.SEARCH_BALANCE_URL,WebUtils.buildAllQuery(requestMap, SmsConstants.CHARSET_UTF8), SmsConstants.CHARSET_UTF8, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }

        StringBuffer returnJson = new StringBuffer().append("{");
        String state = null;
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            NodeList rootList =  parser.getList(parser.getDoc(), "CRemain");
            for (int i = 0; i < rootList.getLength(); i++) {
                Node root = rootList.item(i);
                state = parser.getString(root,"State");
                String balance = parser.getString(root,"Remain");
                String money = "0";
                if(!StringUtils.isEmpty(balance) && params.get("unitPrice") != null){
                	money = String.format("%.2f",Double.parseDouble((String) params.get("unitPrice")) * Double.parseDouble(balance));
                }
                if (i==0){
                    returnJson.append("\"money\"").append(":\"").append(money).append("\",");
                    returnJson.append("\"balance\"").append(":\"").append(balance).append("\"");
                }
            }
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        if("-99".equals(state)){
        	throw  new Exception("短信平台异常");
        }
        if("-3".equals(state)){
        	throw  new Exception("用户名或者密码不正确");
        }
        if("-4".equals(state)){
        	throw  new Exception("产品编号不正确");
        }
        returnJson.append("}");
        return returnJson.toString();
    }

	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
    
    @Override
    public String queryCollect(Map<String, Object> params) throws Exception {
		return null;
    }

	@Override
	public String querySendRecordInfo(Map<String, Object> params)
			throws Exception {
		String sname = params.get("loginName") == null ? "" : params.get("loginName").toString();
		String spwd = params.get("loginPassword") == null ? "" : params.get("loginPassword").toString();
		String mobilePhone = params.get("mobilePhone") == null ? "" : params.get("mobilePhone").toString();
		String msgcontent = params.get("msgcontent") == null ? "" : params.get("msgcontent").toString();   
		String pageSize = params.get("pageSize") == null ? "20" : params.get("pageSize").toString();   
		String curPage = params.get("curPage") == null ? "1" : params.get("curPage").toString();   
		String startTime = params.get("startTime")==null ? "":params.get("startTime").toString();
        String endTime = params.get("endTime")==null ? "":params.get("endTime").toString();
		
		if (StringUtils.isEmpty(sname)) {
			throw new Exception("参数:租户名系统错误:error:租户名不能为空");
		}
		if (StringUtils.isEmpty(spwd)) {
			throw new Exception("参数:租户密码系统错误:error:租户密码不能为空");
		}
		if (!isInteger(pageSize)) {
			throw new Exception("参数:pageSize非法字符");
		}
		if (!isInteger(curPage)) {
			throw new Exception("参数:curPage非法字符");
		}
		
		if (StringUtils.isEmpty(startTime)){
			startTime = DateTimeUtils.format(new Date(),"yyyy-MM-dd")+" 00:00:00";
		} else {
            if(startTime.length()!=14){
                throw  new Exception("参数:开始时间系统错误:error:时间格式不正确");
            }
            startTime = DateTimeUtils.format(DateTimeUtils.toDate(startTime,"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm:ss");
        }
        if (StringUtils.isEmpty(endTime)){
        	endTime =  DateTimeUtils.format(new Date(),"yyyy-MM-dd")+" 23:59:59";
        }else{
            if(endTime.length()!=14){
                throw  new Exception("参数:结束时间系统错误:error:时间格式不正确");
            }
            endTime =  DateTimeUtils.format(DateTimeUtils.toDate(endTime,"yyyyMMddHHmmss"),"yyyy-MM-dd HH:mm:ss");
        }
         
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("accountId", sname);//用户姓名
		requestMap.put("accountPassWord", spwd);//密码
		requestMap.put("productextendId", WelinkConstants.SPRDID);//产品编号
		requestMap.put("msgid", "");//信息编号
		requestMap.put("mobilePhone", mobilePhone);//接收号码
		requestMap.put("msgcontent", msgcontent);//发送内容
		requestMap.put("pageSize", pageSize);//发送内容
		requestMap.put("curPage", curPage);//发送内容
		requestMap.put("startTime", startTime);//发送内容
		requestMap.put("endTime", endTime);//发送内容
        
        String returnMsg = "";
        try {
        	returnMsg = WebUtils.doPost(WelinkConstants.SEARCH_RESULT_URL,WebUtils.buildAllQuery(requestMap, SmsConstants.CHARSET_UTF8), SmsConstants.CHARSET_UTF8, 10000, 10000);
        }catch(Exception e){
            throw  new Exception("调用查询接口失败");
        }
        StringBuffer returnJson = new StringBuffer().append("[");//返回json串
        String state = null;
        try {
            //解析返回XML字符串
            XMLParser parser =  XMLParser.getInstance();
            parser.parse(returnMsg);
            
            if (returnMsg.indexOf("<errorid>")>0){//错误捕获
            	NodeList rootList = parser.getList(parser.getDoc(), "SingleMsgInfo/error");
            	Node root = rootList.item(0);
            	state = parser.getString(root,"errorid");
            }
            
            NodeList rootList =  parser.getList(parser.getDoc(), "SingleMsgInfo/result/SingleResult");
            for (int i = 0; i < rootList.getLength(); i++) {
            	returnJson.append("{");
                Node root = rootList.item(i);
                String accountId = parser.getString(root,"AccountId");//用户帐号
                mobilePhone = parser.getString(root,"MobilePhone");//手机号码
                String msgContent = parser.getString(root,"MsgContent");//信息内容
                String commitTime = parser.getString(root,"CommitTime");//提交时间
                String sendedTime = parser.getString(root,"SendedTime");//发送时间
                String sendState = parser.getString(root,"SendState");//发送状态
                returnJson.append("\"accountId\"").append(":\"").append(accountId).append("\",");
                returnJson.append("\"mobilePhone\"").append(":\"").append(mobilePhone).append("\",");
                returnJson.append("\"msgContent\"").append(":\"").append(msgContent).append("\",");
                returnJson.append("\"commitTime\"").append(":\"").append(commitTime).append("\",");
                returnJson.append("\"sendedTime\"").append(":\"").append(sendedTime).append("\",");
                returnJson.append("\"sendState\"").append(":\"").append(sendState).append("\"");
                returnJson.append("},");
            }
            if (returnJson.lastIndexOf(",") == returnJson.length()-1) {
            	returnJson.deleteCharAt(returnJson.lastIndexOf(","));
			}
        }catch(Exception e){
            throw  new Exception("解析XML失败");
        }
        if (getErrorInfo(state)!=null) {
        	throw  new Exception(getErrorInfo(state));
		}

        returnJson.append("]");
        return returnJson.toString();
	}
	
	public String getErrorInfo(String code){
		if ("100".equals(code)) return "您无权访问";
		if ("101".equals(code)) return "提交参数不可为空，或参数格式错误";
		if ("103".equals(code)) return "调用速度超过限制";
		if ("105".equals(code)) return "查询日期不能为空";
		if ("106".equals(code)) return "查询参数不能为空";
		if ("107".equals(code)) return "查询日期格式有误，正确格式为：yyyy-MM-dd";
		if ("109".equals(code)) return "不能查询超过31天的数据";
		if ("111".equals(code)) return "手机号码必须为数字";
		if ("110".equals(code)) return "系统错误";
		if ("1030".equals(code)) return "用户名密码不正确";
		if ("-1".equals(code)) return "异常返回";
		return null;
	}
}
